package service;

import dao.UserDao;
import domain.User;
import exception.LogException;
import exception.RegisterException;
import utils.MailUtils;
import utils.ResponseCode;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.sql.SQLException;


public class UserService {
    private UserDao userDao=new UserDao();
    public void activeUser(String activeCode) throws RegisterException,  SQLException {
        userDao.activeUser(activeCode);
    }
    public void register(User user) throws RegisterException {
        User userDB=null;
        try {
             userDB = userDao.findUserByUsername(user.getUsername());
        }catch (SQLException e){
            throw new RegisterException(ResponseCode.ERROR_DB);
        }
        if (userDB ==null){//我在数据库中没有找到该用户名，可以注册
            try {
                userDao.addUser(user);//发送一封邮件
                String msg="感谢您注册网上书城，点击"
                        + "<a href='http://localhost:8080/api/activeUser?activeCode="
                        + user.getActiveCode() + "'>&nbsp;激活&nbsp;</a>后使用。"
                        + "<br />为保障您的账户安全，请在24小时内完成激活操作";
                MailUtils.sendMail(user.getEmail(),msg);
            }catch (SQLException e){
                throw new RegisterException(ResponseCode.ERROR_DB);
            } catch (AddressException e) {
                //删除已插入的记录
                try {
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee){
                    throw new RegisterException(ResponseCode.ERROR_DB);
                }
                throw new RegisterException(ResponseCode.ERROR_EMAIL_ADDRESS);
            } catch (MessagingException e) {
                try {
                    
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee){

                }
                throw new RegisterException(ResponseCode.ERROR_EMAIL_SEND);
            }
        }else {//存在相同用户名，请更换用户名
            throw new RegisterException(ResponseCode.ERROR_USERNAME);

        }    }
    public void login(User user) throws LogException{
        try {
            User userDB = userDao.findUserByUsername(user.getUsername());
            if (userDB == null) {//没有该用户或者密码不对
                throw new LogException(ResponseCode.NOT_USER_OR_PASSWORD);
            } else {//找到这个用户，密码不正确
                if (userDB.getState()==1){

                }else {
                    throw new LogException(ResponseCode.NOT_ACTIVE);
                }
            }
        }catch (SQLException e){
            e.printStackTrace();
            throw new LogException(ResponseCode.ERROR_DB);
        }
    }
}
